package web.servlet5;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.alibaba.fastjson.JSON;
import model.CartItem;
import model.Order;
import model.ReceiveAddress;
import model.User;
import sevice.ReceiveAddressService;
import sevice.ServiceDAOFactory;

@WebServlet("/order.do")
public class OrderServlet extends HttpServlet {
	private static final long serialVersionUID = 5281685395163193062L;
	private static final String METHOD_C = "0";
	private static final String METHOD_S = "1";
	private static final String METHOD_A = "2";
	private static final String METHOD_F = "3";

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		HttpSession session = req.getSession();

		@SuppressWarnings("unchecked")
		Map<Integer, CartItem> map = (Map<Integer, CartItem>) session.getAttribute("s_car");
		if (method != null) {
			switch (method) {
			case OrderServlet.METHOD_C:
				confirm(req, resp, map);
				break;
			case OrderServlet.METHOD_S:
				submit(req, resp);
				break;
			case OrderServlet.METHOD_A:
				address(req, resp);
				break;
			case OrderServlet.METHOD_F:
				finish(req, resp);
				break;
			default:
				break;

			}
		}
	}

	private void confirm(HttpServletRequest req, HttpServletResponse resp, Map<Integer, CartItem> map)
			throws ServletException, IOException {
		req.setAttribute("totalDang", total(map));
		req.setAttribute("s_car", map);
		req.getRequestDispatcher("/WEB-INF/view/order/order_info.jsp").forward(req, resp);

	}

	@SuppressWarnings("static-access")
	public double total(Map<Integer, CartItem> map) {
		double totalPrice = 0.0;
		for (Map.Entry<Integer, CartItem> entry : map.entrySet()) {
			totalPrice += entry.getValue().getNum() * entry.getValue().getPro().getDangPrice();
		}
		BigDecimal bd = new BigDecimal(totalPrice);

		BigDecimal bd1 = bd.setScale(2, bd.ROUND_HALF_UP);
		return bd1.doubleValue();
	}

	private void submit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.getRequestDispatcher("/WEB-INF/view/order/address_form.jsp").forward(req, resp);
	}

	private void address(HttpServletRequest req, HttpServletResponse resp) {
		int userId = ((User) req.getSession().getAttribute("s_user")).getId();
		List<ReceiveAddress> addrs;
		try {
			addrs = ServiceDAOFactory.getReceiveAddressService().finByUserId(userId);
			com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
			com.alibaba.fastjson.JSONArray array = new com.alibaba.fastjson.JSONArray();
			for (ReceiveAddress receiveAddress : addrs) {
				com.alibaba.fastjson.JSONObject json1 = (com.alibaba.fastjson.JSONObject) JSON.toJSON(receiveAddress);
				array.add(json1);
			}
			json.put("addrs", array);
			PrintWriter out = resp.getWriter();
			out.print(json.toString());
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	private void finish(HttpServletRequest req, HttpServletResponse resp) {
		ReceiveAddress addr = new ReceiveAddress();
		Order order = new Order();
		HttpSession session = req.getSession();
		try {

			String receiveName = req.getParameter("receiveName");
			String fullAddress = req.getParameter("fullAddress");
			String postalCode = req.getParameter("postalCode");
			String phone = req.getParameter("phone");
			String moblie = req.getParameter("mobile");
			int userId = ((User) session.getAttribute("s_user")).getId();
			Map<Integer, CartItem> map = (Map<Integer, CartItem>) session.getAttribute("s_car");
			if (map.isEmpty()) {

			}
			addr.setUserId(userId);
			addr.setFullAddress(fullAddress);
			addr.setReceiveName(receiveName);
			addr.setPhone(phone);
			addr.setPostalCode(postalCode);
			addr.setMoblie(moblie);

			order = new Order();
			order.setFullAddress(addr.getFullAddress());
			order.setUserId(userId);
			order.setMoblie(addr.getMoblie());
			order.setOrderDesc("desc demo");
			order.setOrderTime(System.currentTimeMillis());
			order.setPhone(addr.getPhone());
			order.setPostalCode(addr.getPostalCode());
			order.setReceiveName(addr.getReceiveName());
			order.setStatus(0);
			order.setTotalPrice(total(map));
			ReceiveAddressService service = ServiceDAOFactory.getReceiveAddressService();
			if (service.finById(addr.getId()) == null) {
				service.save(addr);
			}
			ServiceDAOFactory.getOrderService().save(order);
			map.clear();
			session.setAttribute("s_car", map);
			Order orders = ServiceDAOFactory.getOrderService().finById(order.getOrderTime());
			req.setAttribute("orderId", orders.getId());
			req.setAttribute("totalPrice", order.getTotalPrice());
			req.getRequestDispatcher("/WEB-INF/view/order/order_ok.jsp").forward(req, resp);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
